package cn.com.anysdk.sms.impl;

import cn.com.anysdk.sms.api.ISmsConfig;
import cn.com.anysdk.sms.api.ISmsService;
import cn.com.anysdk.sms.api.SmsRequest;
import cn.com.anysdk.sms.api.SmsResponse;
import cn.com.anysdk.sms.config.AliyunSmsConfig;
import cn.com.anysdk.sms.exception.SmsException;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsRequest;
import com.aliyun.dysmsapi20170525.models.QuerySendDetailsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 阿里云短信服务实现，负责对接阿里云短信SDK，实现短信发送、批量发送、状态查询等功能。
 */
public class AliyunSmsService implements ISmsService {

    private static final Logger logger = LoggerFactory.getLogger(AliyunSmsService.class);

    private final AliyunSmsConfig config;
    private final Client client;

    /**
     * 构造方法，初始化配置和阿里云短信客户端
     * @param config 阿里云短信配置
     * @throws Exception 初始化Client失败时抛出
     */
    public AliyunSmsService(AliyunSmsConfig config) throws Exception {
        this.config = config;
        this.client = config.createClient();
        logger.info("AliyunSmsService initialized with config: {}", config);
    }

    /**
     * 发送单条短信
     * @param request 短信请求参数
     * @return 短信响应
     */
    @Override
    public SmsResponse send(SmsRequest request) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        try {
            logger.debug("Sending SMS to {}, signName={}, templateId={}", 
                request.getPhoneNumber(), request.getSignName(), request.getTemplateId());
            sendSmsRequest.setPhoneNumbers(request.getPhoneNumber())
                    .setSignName(request.getSignName())
                    .setTemplateCode(request.getTemplateId())
                    .setTemplateParam(convertTemplateParms(request.getTemplateParams()));
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            logger.info("SMS sent, response: {}", sendSmsResponse.getBody());
            return toSmsResponse(sendSmsResponse);

        }catch (Exception e) {
            logger.error("Send sms failed, request: {}", request, e);
            throw new SmsException("Send sms failed", e);
        }
    }

    /**
     * 批量发送短信
     * @param requests 短信请求列表
     * @return 响应列表
     */
    @Override
    public List<SmsResponse> sendBatch(List<SmsRequest> requests) {
        logger.debug("Batch sending {} SMS messages", requests.size());
        return requests.stream().map(this::send).toList();
    }

    /**
     * 查询短信发送状态
     * @param messageId 短信消息ID
     * @return 查询结果
     */
    @Override
    public SmsResponse queryStatus(String messageId) {
        try {
            logger.debug("Querying SMS status for messageId={}", messageId);
            QuerySendDetailsRequest request = new QuerySendDetailsRequest()
                .setBizId(messageId);
            QuerySendDetailsResponse response = client.querySendDetails(request);
            logger.info("Query result: {}", response.getBody());
            return toSmsResponse(response);
        }catch (Exception e) {
            logger.error("Query sms status failed, messageId={}", messageId, e);
            throw new SmsException("Query sms status failed", e);
        }
    }

    /**
     * 获取服务商类型
     * @return 服务商类型字符串
     */
    @Override
    public String getProviderType() {
        return "aliyun";
    }

    /**
     * 获取当前配置
     * @return 配置对象
     */
    @Override
    public ISmsConfig getConfig() {
        return config;
    }

    /**
     * 将模板参数Map转换为JSON字符串
     * @param parms 模板参数
     * @return JSON字符串
     */
    private String convertTemplateParms(Map<String,String> parms) {
        if (parms == null || parms.isEmpty()) {
            return "{}";
        }
        return "{" + parms.entrySet().stream()
                .map(e -> "\"" + e.getKey() + "\":\"" + e.getValue() + "\"")
                .collect(Collectors.joining(",")) + "}";
    }

    /**
     * 将阿里云发送短信响应转换为通用SmsResponse
     * @param response 阿里云发送短信响应
     * @return 通用响应
     */
    private SmsResponse toSmsResponse(SendSmsResponse response) {
        boolean success = "OK".equals(response.getBody().getCode());
        return SmsResponse.builder()
                .success(success)
                .messageId(response.getBody().getBizId())
                .errorCode(success ? null : response.getBody().getCode())
                .errorMessage(success ? null : response.getBody().getMessage())
                .providerCode(response.getBody().getCode())
                .sendTime(LocalDateTime.now())
                .status(success ? "SENT" : "FAILED")
                .build();
    }

    /**
     * 将阿里云查询短信响应转换为通用SmsResponse
     * @param response 阿里云查询短信响应
     * @return 通用响应
     */
    private SmsResponse toSmsResponse(QuerySendDetailsResponse response) {
        boolean success = "OK".equals(response.getBody().getCode());
        return SmsResponse.builder()
                .success(success)
                .errorCode(success ? null : response.getBody().getCode())
                .errorMessage(success ? null : response.getBody().getMessage())
                .providerCode(response.getBody().getCode())
                .sendTime(LocalDateTime.now())
                .status(success ? "SENT" : "FAILED")
                .build();
    }
}
